﻿using Hehq.Thirdservice.Wx.Services.Mp.Models;
using Infrastructure.http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Extensions.JsonObjExt;
using System.Security.Cryptography;

namespace Hehq.Thirdservice.Wx.Services.Mp.Impl
{
    public class LoginService: AbsService, ILoginService
    {
        public LoginSuccess ByCode(string code, string appId, string secret)
        {
            string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";

            HttpHelper helper = new HttpHelper();
            var item = new HttpItem();
            item.URL = url;
            item.Method = "post";
            var rest = helper.GetHtml(item);
            string html = rest.Html;
            if(rest.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var obj = html.ToObject<LoginSuccess>();
                return obj;
            }
            else
            {
                return null;
            }
            
        }


        /// <summary>
        /// 解密小程序手机号
        /// </summary>
        /// <param name="userRepParamrep"></param>
        /// <returns></returns>
        public string GetPhoneNumber(UserRepParamrep userRepParamrep)
        {
            String encryptedData = userRepParamrep.encryptedData;
            String iv = userRepParamrep.iv;
            String session_key = userRepParamrep.session_key;
            try
            {
                byte[] encryData = Convert.FromBase64String(encryptedData);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(session_key);
                rijndaelCipher.IV = Convert.FromBase64String(iv);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);

                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                string phoneNumber = model.phoneNumber;
                //return model.phoneNumber;
                if (string.IsNullOrEmpty(phoneNumber))
                {
                    return "";
                }
                return phoneNumber;
            }
            catch (Exception ex)
            {
                return "";
            }
        }



    }
}
